package com.example.tests;

import static com.example.fw.ContactHelper.MODIFICATION;
import static com.example.tests.ContactDataGenerator.loadContactsFromCsvFile;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.example.utils.SortedListOf;

public class ContactModificationTests extends TestBase {
	
	@DataProvider
	public  Iterator<Object[]>  contactsFromFile() throws IOException{
		return wrapContactsForDataProvider(loadContactsFromCsvFile(new File("contacts.txt"))).iterator();
	}
	
	@Test (dataProvider = "contactsFromFile")
	public void modifySomeContact(ContactData contact){
		// Старый список контактов
		SortedListOf<ContactData> oldList = app.getContactHelper().getUiContacts();
		
		Random rnd = new Random();
		int index = rnd.nextInt(oldList.size() - 1);
		
		// Модификация с проверкой данных
		app.navigateTo().mainPage();
		app.getContactHelper().editContact(index);
		ContactData editUiContact = app.getContactHelper().getEditUIContact();
		ContactData editContact = app.getContactHelper().getEditContact(index);
		assertThat(editUiContact, equalTo(editContact));
		

		app.getContactHelper().fillContactForm(contact, MODIFICATION)
			.submitContactModification()
			.returnToHomePage()
			.rebuildCache();	
		
	    // Новый список контактов
		SortedListOf<ContactData> newList = app.getContactHelper().getContacts();
	    
	    // Сравнение
		assertThat(newList, equalTo(oldList.without(index).withAdded(contact)));
	}

}
